package com.example.kill.controller;

import com.example.kill.pojo.KillOrder;
import com.example.kill.pojo.KillOrderInfo;
import com.example.kill.pojo.KillUser;
import com.example.kill.result.CodeMsg;
import com.example.kill.result.Result;
import com.example.kill.service.GoodsService;
import com.example.kill.service.KillOrderService;
import com.example.kill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/kill")
public class KillController {

    private static Logger LOGGER = LoggerFactory.getLogger(KillController.class);


    @Autowired
    private GoodsService goodsService;

    @Autowired
    private KillOrderService killOrderService;


    @RequestMapping(value = "/do_kill",method = RequestMethod.POST)
    @ResponseBody
    public Result<KillOrderInfo> list(Model model, KillUser user, @RequestParam("goodsId") long goodsId){
        if (user == null){
            return  Result.error(CodeMsg.SESSION_ERROR) ;
        }
        GoodsVo goodsVo =  goodsService.getGoodsVoById(goodsId);
        int stock =  goodsVo.getStockCount();
        if (stock<=0){
            //商品秒杀完毕
            return Result.error(CodeMsg.MIAO_SHA_OVER);
        }
        //防止重复秒杀
        KillOrder killOrders =   killOrderService.getKillOrderByUserIdGoodsId(user.getId(),goodsId);
        if (killOrders!=null){
            return Result.error(CodeMsg.REPEATE_MIAOSHA);
        }

        //减库存 下订单 写入秒杀订单
        KillOrderInfo orderInfo = killOrderService.kill(user,goodsVo);
        return Result.success(orderInfo);
    }





}
